// 门店详情页面
const apiService = require('../../../utils/api.js');
const app = getApp();

Page({
  data: {
    // 系统信息
    statusBarHeight: 0,
    
    // 门店信息
    storeId: '',
    storeInfo: null,
    
    // 页面状态
    isLoading: true,
    
    // 服务列表
    serviceList: [],
    
    // 美容师列表
    beauticianList: [],
    
    // 当前选中的服务类型
    selectedServiceType: 'all',
    
    // 服务类型列表
    serviceTypes: [
      { id: 'all', name: '全部服务' },
      { id: 'grooming', name: '美容护理' },
      { id: 'bathing', name: '洗澡服务' },
      { id: 'nail', name: '修剪指甲' },
      { id: 'dental', name: '口腔护理' },
      { id: 'spa', name: 'SPA护理' }
    ],
    
    // 轮播图片
    bannerImages: [],
    currentBannerIndex: 0
  },

  onLoad(options) {
    // 获取系统信息
    this.getSystemInfo();
    
    // 获取门店ID
    if (options.storeId) {
      this.setData({
        storeId: options.storeId,
        from: options.from || ''
      });
      
      // 加载门店详情
      this.loadStoreDetail();
    } else {
      wx.showToast({
        title: '门店信息错误',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {
    // 页面显示时刷新数据
    if (this.data.storeId) {
      this.loadStoreDetail();
    }
  },

  // 获取系统信息
  getSystemInfo() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });
  },

  // 加载门店详情
  async loadStoreDetail() {
    try {
      this.setData({ isLoading: true });
      
      const storeManager = app.getStoreManager();
      // 使用门店管理器获取门店详情
      const storeData = await storeManager.getStoreById(this.data.storeId);
      
      if (storeData) {
        
        // 处理轮播图片
        const bannerImages = storeData.images || [];
        
        // 处理服务列表
        const serviceList = storeData.services || [];
        
        // 处理美容师列表
        const beauticianList = storeData.beauticians || [];
        
        this.setData({
          storeInfo: storeData,
          bannerImages,
          serviceList,
          beauticianList,
          isLoading: false
        });
      } else {
        console.error('获取门店详情失败:', result.message);
        this.setData({ isLoading: false });
        wx.showToast({
          title: '门店信息加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载门店详情失败:', error);
      this.setData({ isLoading: false });
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    }
  },

  // 加载模拟数据
  loadMockData() {
    const mockStoreInfo = {
      id: this.data.storeId,
      name: '爱宠美容中心',
      address: '北京市朝阳区三里屯街道工体北路8号',
      phone: '010-12345678',
      rating: 4.8,
      reviewCount: 256,
      openTime: '09:00-21:00',
      description: '专业的宠物美容护理中心，拥有多年经验的美容师团队，为您的爱宠提供最贴心的服务。',
      features: ['专业美容师', '进口设备', '安全环保', '一对一服务'],
      location: {
        latitude: 39.9042,
        longitude: 116.4074
      }
    };
    
    const mockBannerImages = [
      '/images/store/store-banner-1.jpg',
      '/images/store/store-banner-2.jpg',
      '/images/store/store-banner-3.jpg'
    ];
    
    const mockServiceList = [
      {
        id: '1',
        name: '基础洗澡',
        type: 'bathing',
        price: 80,
        duration: 60,
        description: '基础清洁洗澡服务，包含吹干造型',
        image: '/images/service/bathing.jpg'
      },
      {
        id: '2',
        name: '精致美容',
        type: 'grooming',
        price: 150,
        duration: 120,
        description: '全套美容护理，包含洗澡、修剪、造型',
        image: '/images/service/grooming.jpg'
      },
      {
        id: '3',
        name: '指甲修剪',
        type: 'nail',
        price: 30,
        duration: 30,
        description: '专业指甲修剪服务',
        image: '/images/service/nail.jpg'
      },
      {
        id: '4',
        name: 'SPA护理',
        type: 'spa',
        price: 200,
        duration: 90,
        description: '高端SPA护理服务，深度清洁放松',
        image: '/images/service/spa.jpg'
      }
    ];
    
    const mockBeauticianList = [
      {
        id: '1',
        name: '张美美',
        avatar: '/images/beautician/avatar-1.jpg',
        level: 'A级美容师',
        experience: '5年经验',
        rating: 4.9,
        specialties: ['造型设计', '毛发护理']
      },
      {
        id: '2',
        name: '李师傅',
        avatar: '/images/beautician/avatar-2.jpg',
        level: '高级洗护师',
        experience: '8年经验',
        rating: 4.8,
        specialties: ['行为训练', '健康检查']
      }
    ];
    
    this.setData({
      storeInfo: mockStoreInfo,
      bannerImages: mockBannerImages,
      serviceList: mockServiceList,
      beauticianList: mockBeauticianList,
      isLoading: false
    });
  },

  // 轮播图变化
  onBannerChange(e) {
    this.setData({
      currentBannerIndex: e.detail.current
    });
  },

  // 服务类型切换
  onServiceTypeChange(e) {
    const serviceType = e.currentTarget.dataset.type;
    this.setData({
      selectedServiceType: serviceType
    });
  },

  // 获取筛选后的服务列表
  getFilteredServices() {
    const { serviceList, selectedServiceType } = this.data;
    if (selectedServiceType === 'all') {
      return serviceList;
    }
    return serviceList.filter(service => service.type === selectedServiceType);
  },

  // 服务卡片点击
  onServiceTap(e) {
    const serviceId = e.currentTarget.dataset.id;
    const service = this.data.serviceList.find(s => s.id === serviceId);
    
    if (service) {
      if (this.data.from === 'booking-form') {
        app.globalData.selectedService = service;
        wx.navigateBack();
      } else {
        // 跳转到预约页面
        wx.navigateTo({
          url: `/pages/booking/booking-form/index?storeId=${this.data.storeId}&serviceId=${serviceId}`
        });
      }
    }
  },

  // 美容师卡片点击
  onBeauticianTap(e) {
    const beauticianId = e.currentTarget.dataset.id;
    // 可以跳转到美容师详情页面或直接预约
    wx.navigateTo({
      url: `/pages/booking/booking-form/index?storeId=${this.data.storeId}&beauticianId=${beauticianId}`
    });
  },

  // 拨打电话
  onCallPhone() {
    const phone = this.data.storeInfo?.phone;
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone,
        fail: (err) => {
          console.error('拨打电话失败:', err);
          wx.showToast({
            title: '拨打失败',
            icon: 'error'
          });
        }
      });
    }
  },

  // 查看地图
  onViewMap() {
    const storeInfo = this.data.storeInfo;
    if (storeInfo && storeInfo.location) {
      wx.openLocation({
        latitude: storeInfo.location.latitude,
        longitude: storeInfo.location.longitude,
        name: storeInfo.name,
        address: storeInfo.address,
        fail: (err) => {
          console.error('打开地图失败:', err);
          wx.showToast({
            title: '打开地图失败',
            icon: 'error'
          });
        }
      });
    }
  },

  // 立即预约
  onBookNow() {
    wx.navigateTo({
      url: `/pages/booking/booking-form/index?storeId=${this.data.storeId}`
    });
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadStoreDetail().finally(() => {
      wx.stopPullDownRefresh();
    });
  }
});